import { useEffect, useState } from "react";
import {
  Tag,
  Input,
  Button,
  Pagination,
  ConfigProvider,
  message,
  Popconfirm,
} from "antd";
import zhCN from "antd/locale/zh_CN";
import { SearchOutlined, PlusOutlined } from "@ant-design/icons";
import { NavLink } from "react-router";
import massage_icon from "@/assets/icon/massage.png";
import change_icon from "@/assets/icon/change.png";
import delete_icon from "@/assets/icon/delete.png";
import dayjs from "dayjs";

import level1 from "@/assets/icon/level1.png";
import level2 from "@/assets/icon/level2.png";
import level3 from "@/assets/icon/level3.png";

import {
  DigitalEmployeesearch,
  DigitalEmployeetype,
  DigitalEmployeerunData,
  DigitalEmployeeLeft,
} from "@/api/Employee/index";
import type {
  PostRequestsearch,
  searchResponse,
  ResultItem,
  typeResponse,
} from "@/api/Employee/type";

import { useDigitalEmployeeStore } from "@/store/employee";

const Informationcard = ({
  onUpdate,
  item,
}: {
  onUpdate: () => void;
  item: ResultItem;
}) => {
  const statusColorMap: Record<string, string> = {
    在岗: "bg-green-500",
    离岗: "bg-gray-400",
    未部署: "bg-red-500",
    升级维护: "bg-yellow-500",
  };

  const handleDelete = async () => {
    try {
      const res = await DigitalEmployeeLeft({ id: item.id });
      if (res.code === 1) {
        message.success("删除成功");
        onUpdate?.(); // 删除后刷新列表
      } else {
        message.error("删除失败: " + res.message);
      }
    } catch (err) {
      console.error(err);
      message.error("接口异常");
    }
  };
  const getIconPath = useDigitalEmployeeStore((state) => state.getIconPath);

  const levelIconMap: Record<string, string> = {
    初级: level1,
    中级: level2,
    高级: level3,
  };

  const levelColorMap: Record<string, string> = {
    初级: "#c77221",
    中级: "#c1cdd8",
    高级: "#fbc54f",
  };

  const changelevel = (level: string) => levelIconMap[level] || null;

  return (
    <div className="flex flex-col h-full bg-[#fff] rounded-20 pt-7 pr-10 pl-7 pb-5">
      <div className="border-b-[1px] border-[#f7f4f4] pb-5 mb-5">
        <div className="item">
          <div className="lable relative">
            <img
              className="w-auto h-15"
              src={getIconPath(item.icon) as string}
              alt=""
            />
            <img
              className="absolute w-5 right-0 top-0"
              src={changelevel(item.level)}
              alt=""
            />
          </div>
          <div className="flex-1 pt-2">
            <div className="w-full flex items-center">
              <div className="text-[18px] font-bold mr-4">{item.name}</div>
              <Tag color={levelColorMap[item.level] || "#108ee9"}>
                {item.level}
              </Tag>
              <div className="status flex items-center ml-auto">
                <span
                  className={`inline-block w-2.5 h-2.5 rounded-full mr-1 ${
                    statusColorMap[item.run_status] || "bg-gray-300"
                  }`}
                ></span>
                <span>{item.run_status}</span>
              </div>
            </div>
            {/* <div className="text-[#999]">{item.id}</div> */}
          </div>
        </div>
        <div className="item">
          <div className="lable">流程:</div>
          <div className="">{item.workflow}</div>
        </div>
        {/* <div className="item">
          <div className="lable">流程:</div>
          <div className="">{item.icon}</div>
        </div> */}
        {/* <div className="item">
          <div className="lable">流程:</div>
          <div className="">{getIconPath(item.icon)}</div>
        </div> */}
        <div className="item">
          <div className="lable">岗位:</div>
          <div className="">{item.position}</div>
        </div>
        <div className="item">
          <div className="lable">创建时间:</div>
          <div className="">
            {dayjs(item.created_at).format("YYYY-MM-DD HH:mm:ss")}
          </div>
        </div>
      </div>
      <div className="flex items-center justify-between h-full">
        <span>
          <NavLink
            to="/employee/information"
            state={{ ...item, change_type: "view" }}
          >
            <img className="h-5 w-auto" src={massage_icon} alt="" />
          </NavLink>
        </span>
        <span>
          <NavLink
            to="/employee/information"
            state={{ ...item, change_type: "edit" }}
          >
            <img className="h-5 w-auto" src={change_icon} alt="" />
          </NavLink>
        </span>
        <Popconfirm
          title="确认删除该数字员工？"
          description="删除后不可恢复，是否继续？"
          onConfirm={handleDelete}
          okText="确认"
          cancelText="取消"
        >
          <span className="cursor-pointer">
            <img className="h-5 w-auto" src={delete_icon} alt="" />
          </span>
        </Popconfirm>
      </div>
    </div>
  );
};

const Employee = () => {
  const [data, setData] = useState<ResultItem[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(6);
  const [name, setName] = useState("");
  const [inputName, setInputName] = useState("");
  const [type, setType] = useState(""); // 选中的type值
  const [typeList, setTypeList] = useState<string[]>([]); // 所有type值

  const [stats, setStats] = useState([
    {
      label: "数字员工数量总数",
      value: 0,
      bgColor: "#a5f4f3",
      tagColor: "#00bbbd",
    },
    {
      label: "数字员工调用次数",
      value: 0,
      bgColor: "#a0effd",
      tagColor: "#00b6d6",
    },
    {
      label: "执行成功率",
      value: "0%",
      bgColor: "#b7e8ff",
      tagColor: "#00a9f9",
    },
    {
      label: "节约人工时长",
      value: "0 小时",
      bgColor: "#c7e3ff",
      tagColor: "#2391ff",
    },
    {
      label: "提升工作效率",
      value: "0%",
      bgColor: "#cfddff",
      tagColor: "#607eff",
    },
  ]);

  const fetchData = async (
    page: number,
    pageSize: number,
    name?: string,
    type?: string
  ): Promise<number> => {
    const params: PostRequestsearch = {
      Page: page,
      PageSize: pageSize,
      name: name?.trim() || undefined,
      workflow: type || undefined,
    };

    try {
      const res: searchResponse = await DigitalEmployeesearch(params);

      if (res.code === 1) {
        setData(res.data.results);
        setTotal(res.data.count);
        return res.data.count;
      }
    } catch (error) {
      console.error("查询失败:", error);
    }

    return 0;
  };

  const getTypeList = async () => {
    try {
      const res: typeResponse = await DigitalEmployeetype();
      if (res.code === 1 && Array.isArray(res.data)) {
        const list = ["全部", ...res.data];
        setTypeList(list);
      } else {
        console.warn("类型列表获取失败，使用默认值");
        setTypeList(["全部"]);
      }
    } catch (err) {
      console.error("获取类型列表失败:", err);
      setTypeList(["全部"]);
    }
  };

  useEffect(() => {
    const init = async () => {
      await fetchData(page, pageSize, name, type);

      await getTypeList();

      try {
        const { data } = await DigitalEmployeerunData();

        setStats([
          {
            label: "数字员工数量总数",
            value: data.digtals,
            bgColor: "#a5f4f3",
            tagColor: "#00bbbd",
          },
          {
            label: "数字员工调用次数",
            value: data.run_count,
            bgColor: "#a0effd",
            tagColor: "#00b6d6",
          },
          {
            label: "执行成功率",
            value: `${data.success_ratio}`,
            bgColor: "#b7e8ff",
            tagColor: "#00a9f9",
          },
          {
            label: "节约人工时长",
            value: `${data.time_savings}`,
            bgColor: "#c7e3ff",
            tagColor: "#2391ff",
          },
          {
            label: "提升工作效率",
            value: `${data.performance_ratio}`,
            bgColor: "#cfddff",
            tagColor: "#607eff",
          },
        ]);
      } catch (err) {
        console.error("获取 runData 失败", err);
      }
    };

    init();
  }, [page, pageSize, name, type]);

  const handleSearch = () => {
    setPage(1);
    setName(inputName);
    refreshList();
  };

  const handleTypeChange = (selectedType: string) => {
    setPage(1);
    setType(selectedType === "全部" ? "" : selectedType);
  };

  const onPageChange = (newPage: number, newPageSize?: number) => {
    setPage(newPage);
    if (newPageSize) setPageSize(newPageSize);
  };

  const refreshList = async () => {
    await fetchData(page, pageSize, name, type);
  };

  return (
    <div className="page-container flex flex-col h-full pb-5">
      <div className="grid grid-cols-5 gap-5">
        {stats.map((item) => (
          <div
            key={item.label}
            className="flex items-center justify-between text-4 pt-3 pb-3 pl-4 pr-4 rounded-10"
            style={{ backgroundColor: item.bgColor }}
          >
            {item.label}
            <span
              className="text-3 text-[#fff] pl-2 pr-2 rounded-10"
              style={{ backgroundColor: item.tagColor }}
            >
              {item.value}
            </span>
          </div>
        ))}
      </div>

      {/* 查询行 */}
      <div className="flex items-center mt-4 mb-4">
        <div className="flex items-center mr-4">
          <span className="mr-2 text-5 whitespace-nowrap">数字员工名称</span>
          <Input
            size="small"
            value={inputName}
            onChange={(e) => setInputName(e.target.value)}
            onPressEnter={handleSearch}
            placeholder="请输入员工名称"
            allowClear
          />
        </div>
        <Button
          size="small"
          className="mr-4 ml-auto"
          type="primary"
          icon={<SearchOutlined />}
          onClick={handleSearch}
        >
          查询
        </Button>
        <NavLink state={{ change_type: "add" }} to="/employee/information">
          <Button size="small" type="primary" icon={<PlusOutlined />}>
            入职
          </Button>
        </NavLink>
      </div>

      {/* 筛选标签 */}
      <div className="mb-4 flex items-center flex-wrap">
        <span className="text-5 mr-3">所属工作流程</span>
        {typeList.map((item) => {
          const selected = (item === "全部" && type === "") || item === type;
          return (
            <div
              key={item}
              className={`text-5 px-3 py-1 rounded-10 cursor-pointer mr-3 ${
                selected ? "bg-[#108ee9] text-white" : ""
              }`}
              onClick={() => handleTypeChange(item)}
            >
              {item}
            </div>
          );
        })}
      </div>

      {/* 卡片展示 */}
      <div className="grid grid-cols-3 gap-5 mb-3">
        {data.map((item) => (
          <Informationcard onUpdate={refreshList} key={item.id} item={item} />
        ))}
      </div>

      {/* 分页 */}
      <div className="mt-auto flex justify-end">
        <ConfigProvider locale={zhCN}>
          <Pagination
            current={page}
            pageSize={pageSize}
            total={total}
            showSizeChanger
            pageSizeOptions={["6", "9", "12", "24"]}
            onChange={onPageChange}
            showTotal={(total, range) =>
              `第 ${range[0]}-${range[1]} 条 / 共 ${total} 条`
            }
          />
        </ConfigProvider>
      </div>
    </div>
  );
};

export default Employee;
